<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAlert,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NPopconfirm,
  NSelect,
  NSwitch,
  NTag,
  NTreeSelect
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'

import { renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'

defineOptions({ name: '定时任务规则' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '定时任务规则',
  initForm: { order: 0 },
  doCreate: api.createJobsRule,
  doUpdate: api.updateJobsRule,
  doDelete: api.deleteJobsRule,
  refresh: () => $table.value?.handlerefresh(),
})

const deptOption = ref([])
const uptypeOption = ref([{"value":1,"label":"自动启动"},{"value":2,"label":"手动启动"}])
const isDisabled = ref(false)

onMounted(() => {
  $table.value?.handleSearch()
  api.getJobsRuleType().then((res) => (deptOption.value = res.data))
})

const deptRules = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['input', 'blur', 'change'],
    },
  ],
  func_name: [
    {
      required: true,
      message: '请输入访问路径',
      trigger: ['input', 'blur', 'change'],
    },
    {
      pattern: /^(https?:\/\/)/,
      message: '访问路径必须以 http:// 或 https:// 开头',
      trigger: ['input', 'blur', 'change'],
    },
  ],
}

async function addDepts() {
  isDisabled.value = false
  handleAdd()
}

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '任务类型',
    key: 'type_name',
    width: 120,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '名称',
    key: 'name',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '访问路径',
    key: 'func_name',
    width: '400',
    align: 'center',
    render(row) {
      return h(
          NAlert,
          {  size: 'small',   style: { margin: '0px' } },
          { default: () => row.func_name }
      )
    },
  },
  {
    title: '规则',
    key: 'rule_name',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
    render(row) {
      return h(
          NTag,
          { type: 'primary', size: 'small', bordered: false, style: { margin: '0px' } },
          { default: () => row.rule_name }
      )
    },
  },

  {
    title: '开关',
    key: 'state',
    width: 50,
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.state,
        loading: !!row.publishing,
        checkedValue: true,
        uncheckedValue: false,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 'auto',
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
            h(
                NButton,
                {
                  size: 'small',
                  type: 'primary',
                  style: 'margin-right: 8px;',
                  onClick: () => {
                    console.log('row', row.parent_id)
                    // if (row.parent_id === 0) {
                    //   isDisabled.value = true
                    // } else {
                    //   isDisabled.value = false
                    // }
                    handleEdit(row)
                  },
                },
                {
                  default: () => '编辑',
                  icon: renderIcon('material-symbols:edit', { size: 16 }),
                }
            ),
            [[vPermission, 'post/api/content/category/update']]
        ),
        h(
            NPopconfirm,
            {
              onPositiveClick: () => handleDelete({ data_id: row.id }, false),
              onNegativeClick: () => {},
            },
            {
              trigger: () =>
                  withDirectives(
                      h(
                          NButton,
                          {
                            size: 'small',
                            type: 'error',
                          },
                          {
                            default: () => '删除',
                            icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                          }
                      ),
                      [[vPermission, 'delete/api/content/category/delete']]
                  ),
              default: () => h('div', {}, '确定删除该任务吗?'),
            }
        ),
      ]
    },
  },
]

// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.state = row.state === false
  row.publishing = false
  try {
    await api.updateJobsRule(row)
    $message?.success(row.state ? '已启动' : '已停止')
    $table.value?.handleSearch()
  } catch (err) {
    // 有异常恢复原来的状态
    row.state = row.state === false
  } finally {
    row.publishing = false
  }
}
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="定时任务规则">
    <template #action>
      <div>
        <NButton
            v-permission="'post/api/content/category/create'"
            class="float-right mr-15"
            type="primary"
            @click="addDepts"
        >
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建任务
        </NButton>
      </div>
    </template>
    <!-- 表格 -->
    <CrudTable
        ref="$table"
        v-model:query-items="queryItems"
        :columns="columns"
        :get-data="api.getJobsRule"
    >
      <template #queryBar>
        <QueryBarItem label="名称" :label-width="80">
          <NInput
              v-model:value="queryItems.name"
              clearable
              type="text"
              placeholder="请输入名称"
              @keypress.enter="$table?.handleSearch()"
          />
        </QueryBarItem>
        <QueryBarItem label="任务类型" :label-width="80">
          <NSelect
              v-model:value="queryItems.type"
              style="width: 150px"
              :options="deptOption"
              clearable
              placeholder="请选类型"
          />
        </QueryBarItem>
      </template>
    </CrudTable>

    <!-- 新增/编辑 弹窗 -->
    <CrudModal
        v-model:visible="modalVisible"
        :title="modalTitle"
        :loading="modalLoading"
        @save="handleSave"
    >
      <NForm
          ref="modalFormRef"
          label-placement="left"
          label-align="left"
          :label-width="80"
          :model="modalForm"
          :rules="deptRules"
      >
<!--        <NFormItem label="任务类型" path="type">-->
<!--          <NSelect-->
<!--              v-model:value="modalForm.type"-->
<!--              :options="deptOption"-->
<!--              placeholder="请选择类型"-->
<!--          />-->
<!--        </NFormItem>-->
        <NFormItem label="任务类型" path="type">
              <n-radio-group
                v-model:value="modalForm.type"
                name="radiogroup"
                :default-value="1"
              >
                <n-space>
                  <n-radio v-for="item in deptOption" :key="item.value" :value="item.value">
                    {{ item.label }}
                  </n-radio>
                </n-space>
              </n-radio-group>
            </NFormItem>
        <NFormItem label="启动方式" path="up_type">
              <n-radio-group
                v-model:value="modalForm.up_type"
                name="radiogroup"
                :default-value="1"
              >
                <n-space>
                  <n-radio v-for="item in uptypeOption" :key="item.value" :value="item.value">
                    {{ item.label }}
                  </n-radio>
                </n-space>
              </n-radio-group>
            </NFormItem>

        <NFormItem label="任务名称" path="name">
          <NInput v-model:value="modalForm.name" clearable placeholder="请输入名称" />
        </NFormItem>
        <NFormItem label="访问路径" path="func_name">
          <NInput v-model:value="modalForm.func_name" clearable placeholder="https://" />
        </NFormItem>

        <NFormItem label="频率(秒)" path="times" v-if="modalForm.type===1">
          <NInputNumber v-model:value="modalForm.times" clearable placeholder="请输入执行频率" min="1"/>
        </NFormItem>

        <NFormItem label="执行日期" path="day" v-if="modalForm.type===2">
          <NInputNumber v-model:value="modalForm.day" clearable placeholder="执行日期" min="0"/>&nbsp;
          <n-tag size="large" type="success">每月几号,0代表每天都执行</n-tag>
        </NFormItem>
        <NFormItem label="执行时" path="hour" v-if="modalForm.type===2">
          <NInputNumber v-model:value="modalForm.hour" clearable placeholder="执行时" min="0"/>&nbsp;
          <n-tag type="success" size="large">每天执行的整点</n-tag>
        </NFormItem>
        <NFormItem label="执行分" path="minute" v-if="modalForm.type===2">
          <NInputNumber v-model:value="modalForm.minute" clearable placeholder="执行分" min="0"/>&nbsp;
          <n-tag type="success" size="large">每天执行的分点</n-tag>
        </NFormItem>
        <NFormItem label="执行秒" path="second" v-if="modalForm.type===2">
          <NInputNumber v-model:value="modalForm.second" clearable placeholder="执行秒" min="0"/>&nbsp;
          <n-tag type="success" size="large">每天执行的秒点</n-tag>
        </NFormItem>


      </NForm>
    </CrudModal>
  </CommonPage>
</template>
